package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.task.WebSocketTask;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 用户提交订单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {

        // 不可提交订单的情况 1.收货地址为空 2.超出配送范围 3.购物车为空
        // 查收货地址是否为空
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if(addressBook == null){
            // 说明不存在收货地址 不能提交订单 抛出异常
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        // 查购物车是否为空 先获取用户id 然后到购物车表中查
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);

        if(shoppingCartList == null && shoppingCartList.size() == 0){
            // 说明用户的购物车为空 不能下单
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        // 构造订单数据 需要去获取购物车和收货地址的属性
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, order);
        order.setPhone(addressBook.getPhone());
        order.setAddress(addressBook.getDetail());
        order.setConsignee(addressBook.getConsignee());
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        order.setUserId(BaseContext.getCurrentId());
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setPayStatus(Orders.UN_PAID);
        order.setOrderTime(LocalDateTime.now());

        // 向订单表插入数据
        orderMapper.insert(order);

        // 构造订单明细数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for(ShoppingCart cart : shoppingCartList){
            // 新建一个订单明细对象
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(order.getId());

            // 添加到订单明细表中
            orderDetailList.add(orderDetail);
        }

        // 将所有的订单明细添加到订单明细表中
        orderDetailMapper.insertBatch(orderDetailList);

        // 添加订单明细之后 需要清空购物车
        shoppingCartMapper.deleteById(BaseContext.getCurrentId());

        // 封装返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(order.getId())
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .orderTime(order.getOrderTime())
                .build();

        return orderSubmitVO;
    }

    /**
     * 订单支付修改版
     * @param ordersPaymentDTO
     * @return
     */
    @Override
    public OrdersSubmitModifyDTO submitOrderModify(OrdersPaymentDTO ordersPaymentDTO) {
        OrdersSubmitModifyDTO  ordersSubmitModifyDTO = new OrdersSubmitModifyDTO();
        paySuccess(ordersPaymentDTO.getOrderNumber());
        /*  获取预计送达时间*/
        Orders ordersDB = orderMapper.getByNumber(ordersPaymentDTO.getOrderNumber());
        ordersSubmitModifyDTO.setEstimatedDeliveryTime(ordersDB.getEstimatedDeliveryTime());
        return ordersSubmitModifyDTO;
    }



    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        // 支付成功之后，发送消息给商家
        HashMap map = new HashMap<>();
        map.put("type", 1); // 消息类型 1 表示来单提醒
        map.put("orderId", orders.getId()); // 订单id
        map.put("content", outTradeNo); // 消息内容 订单号

        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * 历史订单查询-用户端
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult getHistoryOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        // 设置分页 页码和每页展示多少条数据
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());

        // 获取分页数据
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> list = new ArrayList<>();

        // 查出订单明细，封装到VO传给前端
        if (page != null && page.size() > 0) {
            for (Orders orders : page) {
                Long ordersId = orders.getId();

                List<OrderDetail> orderDetail = orderDetailMapper.getByOrderId(ordersId);

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetail);

                list.add(orderVO);
            }
        }

        return new PageResult(page.getTotal(), list);
    }

    /**
     *  查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO getOrderById(Long id) {

        // 根据id查询订单信息
        Orders orders  = orderMapper.getOrderById(id);

        // 查询订单对应的菜品数据
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

        // 将订单菜品数据封装到orderVO中
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    /**
     * 用户端-取消订单
     * @param id
     */
    @Override
    public void cancel(Long id) {
        /**
         * 订单状态： 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
         * 1、查询订单状态
         * 2、如果是待付款状态，则修改订单状态为取消状态，并返回取消成功的结果
         * 3、如果是待接单、已接单、派送中状态，则不能取消订单，需要返回一个错误结果
         * 4、如果是已完成、已取消状态，则不能取消订单，需要返回一个错误结果
         * 5、如果是待接单状态，则修改订单状态为取消状态，并返回取消成功
         * 6、如果是已接单状态，则修改订单状态为派送中，并返回派送中成功
         * 7、如果是派送中状态，则修改订单状态为已完成，并返回完成成功
         * 8、如果是已完成状态，则不能取消订单，需要返回一个错误结果
         * 9、如果是已取消状态，则不能取消订单，需要返回一个错误结果
         */

        // 1.查询订单状态
        OrderVO orderById = orderMapper.getOrderById(id);
        Integer status = orderById.getStatus();

        // 还要判断订单是否存在，订单存在才能下一步判断订单状态
        if (orderById == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        // 2.判断订单状态（是否可以删除订单）
        if (status > 2) {
            // 不可以删除 抛出异常
            throw new DeletionNotAllowedException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 3.可以删除订单
        if (status == 1 || status == 2){
            orderById.setStatus(Orders.CANCELLED);
            orderById.setCancelReason("用户取消");
            orderById.setCancelTime(LocalDateTime.now());
            orderMapper.update(orderById);
        }else {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
    }

    /**
     * 再来一单
     * @param id
     */
    @Override
    public void repetition(Long id) {
        /*// 再来一单
        // 需要操作两个表 订单表、订单明细表

        // 1. 查询原订单
        OrderVO oldOrder = orderMapper.getOrderById(id);
        if (oldOrder == null) {
            throw new RuntimeException("原订单不存在");
        }

        // 2. 复制订单数据
        Orders newOrder = new Orders();
        BeanUtils.copyProperties(oldOrder, newOrder, "id", "number", "status", "orderTime", "checkoutTime", "payStatus");
        newOrder.setNumber(String.valueOf(System.currentTimeMillis())); // 重新生成订单号
        newOrder.setStatus(Orders.PENDING_PAYMENT); // 设置为待付款
        newOrder.setOrderTime(LocalDateTime.now());
        newOrder.setPayStatus(Orders.UN_PAID);

        // 3. 插入新订单
        orderMapper.insert(newOrder);

        // 4. 查询原订单明细
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(id);

        // 5. 复制订单明细
        List<OrderDetail> newOrderDetails = orderDetails.stream().map(item -> {
            OrderDetail detail = new OrderDetail();
            BeanUtils.copyProperties(item, detail, "id");
            detail.setOrderId(newOrder.getId());
            return detail;
        }).collect(Collectors.toList());

        // 6. 批量插入订单明细
        orderDetailMapper.insertBatch(newOrderDetails);*/

        // 1. 查询原订单
        OrderVO oldOrder = orderMapper.getOrderById(id);
        if (oldOrder == null) {
            throw new RuntimeException("原订单不存在");
        }

        // 2. 查询原订单明细
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(id);
        if (orderDetails == null || orderDetails.isEmpty()) {
            throw new RuntimeException("原订单没有明细");
        }

        // 3. 获取当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 4. 将订单明细转换为购物车对象
        List<ShoppingCart> shoppingCartList = orderDetails.stream().map(detail -> {
            ShoppingCart cart = new ShoppingCart();
            // 复制属性
            BeanUtils.copyProperties(detail, cart, "id");
            // 手动补充购物车需要的字段
            cart.setId(null); // 让数据库自增
            cart.setUserId(userId);
            cart.setCreateTime(LocalDateTime.now());
            cart.setDishId(detail.getDishId());
            cart.setSetmealId(detail.getSetmealId());
            cart.setName(detail.getName());
            cart.setImage(detail.getImage());
            cart.setDishFlavor(detail.getDishFlavor());
            cart.setNumber(detail.getNumber());
            cart.setAmount(detail.getAmount());
            return cart;
        }).collect(Collectors.toList());

        // 5. 批量插入购物车
        shoppingCartMapper.insertBatch(shoppingCartList);

    }

    /**
     * 订单搜索
     *
     * @param ordersPageQueryDTO
     * @return
     */
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        // 部分订单状态，需要额外返回订单菜品信息，将Orders转化为OrderVO
        List<OrderVO> orderVOList = getOrderVOList(page);

        return new PageResult(page.getTotal(), orderVOList);
    }

    /**
     * 各个状态的订单数量统计
     *
     * @return
     */
    public OrderStatisticsVO statistics() {
        // 根据状态，分别查询出待接单、待派送、派送中的订单数量
        Integer toBeConfirmed = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed = orderMapper.countStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);

        // 将查询出的数据封装到orderStatisticsVO中响应
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }


    @Override
    public OrderVO details(Long orderId) {

        //先查询订单信息
        Orders orders = orderMapper.getById(orderId);

        //再查询订单明细
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);

        //封装入OrderVO并返回
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetails);

        return orderVO;
    }

    private List<OrderVO> getOrderVOList(Page<Orders> page) {
        // 需要返回订单菜品信息，自定义OrderVO响应结果
        List<OrderVO> orderVOList = new ArrayList<>();

        List<Orders> ordersList = page.getResult();
        if (!CollectionUtils.isEmpty(ordersList)) {
            for (Orders orders : ordersList) {
                // 将共同字段复制到OrderVO
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                String orderDishes = getOrderDishesStr(orders);

                // 将订单菜品信息封装到orderVO中，并添加到orderVOList
                orderVO.setOrderDishes(orderDishes);
                orderVOList.add(orderVO);
            }
        }
        return orderVOList;
    }

    /**
     * 根据订单id获取菜品信息字符串
     *
     * @param orders
     * @return
     */
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }

    /**
     * 接单
     *
     * @param ordersConfirmDTO
     */
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();

        orderMapper.update(orders);
    }

    /**
     * 拒单
     *
     * @param ordersRejectionDTO
     */
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(ordersRejectionDTO.getId());

        // 订单只有存在且状态为2（待接单）才可以拒单
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //支付状态
        /*Integer payStatus = ordersDB.getPayStatus();
        if (payStatus == Orders.PAID) {
            //用户已支付，需要退款
            String refund = weChatPayUtil.refund(
                    ordersDB.getNumber(),
                    ordersDB.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));
            log.info("申请退款：{}", refund);
        }*/

        //支付状态
        Integer payStatus = ordersDB.getPayStatus();
        if (payStatus == Orders.PAID) {
            // 用户已支付，需要退款 - 简单模拟处理
            log.info("订单已支付，正在处理退款: 订单号={}", ordersDB.getNumber());
            // 模拟退款成功，实际项目中这里应该调用真实的退款接口
            log.info("退款处理完成: 订单号={}", ordersDB.getNumber());
        }


        // 拒单需要退款，根据订单id更新订单状态、拒单原因、取消时间
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());

        orderMapper.update(orders);
    }

    /**
     * 取消订单
     *
     * @param ordersCancelDTO
     */
    public void cancel(OrdersCancelDTO ordersCancelDTO) throws Exception {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(ordersCancelDTO.getId());

        //支付状态
        Integer payStatus = ordersDB.getPayStatus();
        if (payStatus == 1) {
            //用户已支付，需要退款
            String refund = weChatPayUtil.refund(
                    ordersDB.getNumber(),
                    ordersDB.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));
            log.info("申请退款：{}", refund);
        }

        // 管理端取消订单需要退款，根据订单id更新订单状态、取消原因、取消时间
        Orders orders = new Orders();
        orders.setId(ordersCancelDTO.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 派送订单
     *
     * @param id
     */
    public void delivery(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);

        // 校验订单是否存在，并且状态为3
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        // 更新订单状态,状态转为派送中
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);

        orderMapper.update(orders);
    }

    /**
     * 完成订单
     *
     * @param id
     */
    public void complete(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);

        // 校验订单是否存在，并且状态为4
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        // 更新订单状态,状态转为完成
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());

        orderMapper.update(orders);
    }

    /**
     * 订单催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        Orders reminder = orderMapper.reminder(id);
        // 支付成功之后，发送消息给商家
        HashMap map = new HashMap<>();
        map.put("type", 2); // 消息类型 2 催单提醒
        map.put("orderId", reminder.getId()); // 订单id
        map.put("content", "订单催单:" + reminder.getId()); // 消息内容 订单号

        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

}
